$(document).ready(function(){
	// 筛选条件下拉框初始化
	initFilters();
	
	// 筛选按钮
	$("#btnFilter").click(function(){
		filterRecords();
	});

	// 登记新资助人按钮
	$("#bthAdd").click(function(){
		popupAddDialog();
	});
	
	// 对话框中的各下拉选择框初始化
	initDialogOptions();
	
	filterRecords();
});

function initFilters() {
	//var urlBase = location.pathname;
	// 暂无筛选框
}

function filterRecords() {
	var url = getAncestorPath(location.pathname,1);
	var keyword = $("#keyword").val();
	var limit = $("#limit").val();
	limit = (typeof limit == "undefined" || limit == null || limit == "") ? 20 : limit;
	var page = $("#page").val();
	page = (typeof page == "undefined" || page == null || page == "") ? 1 : page;
	var postData = {keyword:keyword, page:page, limit:limit};
	
	$("#txtMessage").text("正在加载...")
    $.ajax({
        type: "GET",
        url: url,
        data: postData,
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var tableBodyObj = $("#tableSponsors tbody");
                tableBodyObj.html("");
                $.each(resp.data.rows, function(index, item) {
                	var rowHtml = "<tr>";
                	rowHtml += "<td>" + item.id + "</td>";
                	rowHtml += "<td>" + item.name + "</td>";
                	rowHtml += "<td>" + item.nickname + "</td>";
                	rowHtml += "<td>" + item.gender + "</td>";
                	rowHtml += "<td>" + item.area + "</td>";
                	rowHtml += "<td>" + item.contactPhone + "</td>";
                	rowHtml += "<td>" + item.contactWechat + "</td>";
                	rowHtml += "<td>";
                	rowHtml += "<span class='clickable' onclick='popupEditDialog(" + item.id + ")'>Edit</span>";
                	rowHtml += "<span class='clickable' onclick='popupDetailsDialog(" + item.id + ")'>详情</span>";
                	rowHtml += "</td>";
                	rowHtml += "</tr>";
                	tableBodyObj.append(rowHtml);
                });
                
                var countSummaryObj = $("#txtCountSummary");
                countSummaryObj.html("共 " + resp.data.total + " 条记录，当前为第 " + resp.data.page + " 页");

                var navObj = $("#pagingNav");
                var urlBase = url + "?keyword=" + keyword + "&limit=" + limit;
                var navHtml = genPagingNavHtml(urlBase, resp.data.total, limit, page);
                //debugger
                navObj.html(navHtml);                
                
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        	$("#txtMessage").text("");
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function navToPage(pageNumber) {
	$("#page").val(pageNumber);
	filterRecords();
}

// 1.url pattern, 2.总记录数(resp.data.total)、每页多少行(limit)、当前第几页(page)
// 以当前页为中心，前5页，后5页；判断最大最小边界
function genPagingNavHtml(urlBase, totalRows, pageSize, curPage) {
	var totalPages = Math.ceil(totalRows/pageSize);
	var step = 5;
	var min = curPage - 5;
	min = min<1 ? 1 : min;
	var max = min + 9;
	max = max>totalPages ? totalPages : max;

	var pagingHtml = "页码：";
	for(i=min; i<=max; i++) {
		if(i != curPage) {
			pagingHtml += "<span class='clickable' onclick='navToPage(" + i + ")'>" + i + "</span>";
		} else {
			pagingHtml += "<span>" + i + "</span>";
		}
	}
	
	return pagingHtml;
}

var sponsorDialog = $("#sponsorDialog").dialog({
    autoOpen: false,
    height:450,
    width: 420,
    modal: true,
	close: function() {}
});

function initDialogOptions() {
}

function popupAddDialog() {
	// 各字段初始化，部分字段可保持上次操作的选项
    $("#sponsorDialog #id").val("");
    $("#sponsorDialog #name").val("");
    $("#sponsorDialog #anonymous").val("");
    $("#sponsorDialog #nickname").val("");
    $("#sponsorDialog #gender").val("");
    $("#sponsorDialog #area").val("");
    //$("#sponsorDialog #type").val("");
    $("#sponsorDialog #contactPhone").val("");
    $("#sponsorDialog #contactWechat").val("");
    $("#sponsorDialog #contactEmail").val("");
    $("#sponsorDialog #contactAddress").val("");
    $("#sponsorDialog #contactOther").val("");
    $("#sponsorDialog #remark").val("");
    
	sponsorDialog = sponsorDialog.dialog({
		label: "登记新资助人",
	    buttons: {
	    	"提交登记信息": addSponsor,
	    	Cancel: function() {
	    		sponsorDialog.dialog("close");
	    	}
	    }
	});
	sponsorDialog.dialog("open");
}

function addSponsor() {
	var name = $("#sponsorDialog #name").val();
	var anonymous = $("#sponsorDialog #anonymous").val();
	var nickname = $("#sponsorDialog #nickname").val();
	var gender = $("#sponsorDialog #gender").val();
	var area = $("#sponsorDialog #area").val();
	var type = $("#sponsorDialog #type").val();
	var contactPhone = $("#sponsorDialog #contactPhone").val();
	var contactWechat = $("#sponsorDialog #contactWechat").val();
	var contactEmail = $("#sponsorDialog #contactEmail").val();
	var contactAddress = $("#sponsorDialog #contactAddress").val();
	var contactOther = $("#sponsorDialog #contactOther").val();
	var remark = $("#sponsorDialog #remark").val();
	var postData = {name:name, anonymous:anonymous, nickname:nickname, gender:gender, area:area, type:type, contactPhone:contactPhone, contactWechat:contactWechat, contactEmail:contactEmail, contactOther:contactOther, contactAddress:contactAddress, remark:remark};
	//debugger
	var url = location.href + "/..";
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	sponsorDialog.dialog("close");
            	filterRecords(); // 刷新页面
                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function popupEditDialog(sponsorId) {
	//debugger
	var url = getAncestorPath(location.pathname,1) + sponsorId;
	ajaxGetData(url, realPopupEditDialog);
}

function realPopupEditDialog(sponsor) {
    $("#sponsorDialog #id").val(sponsor.id);
    $("#sponsorDialog #name").val(sponsor.name);
    $("#sponsorDialog #anonymous").val(sponsor.anonymous);
    $("#sponsorDialog #nickname").val(sponsor.nickname);
    $("#sponsorDialog #gender").val(sponsor.gender);
    $("#sponsorDialog #area").val(sponsor.area);
    $("#sponsorDialog #type").val(sponsor.type);
    $("#sponsorDialog #contactPhone").val(sponsor.contactPhone);
    $("#sponsorDialog #contactEmail").val(sponsor.contactEmail);
    $("#sponsorDialog #contactWechat").val(sponsor.contactWechat);
    $("#sponsorDialog #contactAddress").val(sponsor.contactAddress);
    $("#sponsorDialog #contactOther").val(sponsor.contactOther);
    $("#sponsorDialog #remark").val(sponsor.remark);
	    
	sponsorDialog = sponsorDialog.dialog({
		label: "资助人信息",
	    buttons: {
	    	"保存": updateSponsor,
	    	Cancel: function() {
	    		sponsorDialog.dialog("close");
	    	}
	    }
	});
	sponsorDialog.dialog("open");
}

function updateSponsor() {
	var id = $("#sponsorDialog #id").val();
	var name = $("#sponsorDialog #name").val();
	var anonymous = $("#sponsorDialog #anonymous").val();
	var nickname = $("#sponsorDialog #nickname").val();
	var gender = $("#sponsorDialog #gender").val();
	var area = $("#sponsorDialog #area").val();
	var type = $("#sponsorDialog #type").val();
	var contactPhone = $("#sponsorDialog #contactPhone").val();
	var contactWechat = $("#sponsorDialog #contactWechat").val();
	var contactEmail = $("#sponsorDialog #contactEmail").val();
	var contactAddress = $("#sponsorDialog #contactAddress").val();
	var contactOther = $("#sponsorDialog #contactOther").val();
	var remark = $("#sponsorDialog #remark").val();
	var postData = {name:name, anonymous:anonymous, nickname:nickname, gender:gender, area:area, type:type, contactPhone:contactPhone, contactWechat:contactWechat, contactEmail:contactEmail, contactOther:contactOther, contactAddress:contactAddress, remark:remark};
	debugger
	var url = location.href + "/../" + id;
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	sponsorDialog.dialog("close");
            	filterRecords(); // 刷新页面
                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

// 资助人信息及捐助历史展示
var detailsDialog = $("#detailsDialog").dialog({
    autoOpen: false,
    height:560,
    width: 640,
    modal: true,
	close: function() {}
});


function popupDetailsDialog(sponsorId) {
	debugger
	var sponsorUrl = getAncestorPath(location.pathname,1) + sponsorId;
	ajaxGetData(sponsorUrl, showSponsorInfo);
	var fundHistoryUrl = getAncestorPath(location.pathname,2) + "students-aids?sponsorId=" + sponsorId + "&page=1&limit=9999";
	ajaxGetData(fundHistoryUrl, showFundHistory);
}

function showSponsorInfo(sponsor) {
	var infoHtml = "";
	infoHtml += "id:" + sponsor.id + "</br>";
	infoHtml += "姓名：" + sponsor.name + " &nbsp; 昵称：" + sponsor.nickname + " &nbsp; 匿名：" + sponsor.anonymous + "<br/>";
	infoHtml += "性别：" + sponsor.gender + " &nbsp; 类别：" + sponsor.type + " &nbsp; 地区：" + sponsor.area + "<br/>";
	infoHtml += "联系方式：<br/>";
	infoHtml += "电话：" + sponsor.contactPhone + " &nbsp; 邮箱：" + sponsor.contactEmail + " &nbsp; 微信：" + sponsor.contactWechat + "<br/>";
	infoHtml += "其他：" + sponsor.contactOther + "<br/>";
	infoHtml += "地址：" + sponsor.contactAddress + "<br/>";
	infoHtml += "备注：<br/><textarea rows='5' cols='90'>" + sponsor.remark + "</textarea>" 
	//debugger
	var infoDiv = $("#detailsDialog #sonsporInfo");
	infoDiv.html(infoHtml);

	detailsDialog.dialog("open");
}

function showFundHistory(respData) {
	var tableBody =  $("#detailsDialog #fundHistoryTable tbody");
	tableBody.html("");
	debugger
    $.each(respData.rows, function(index, item) {
    	var rowHtml = "<tr>";
    	rowHtml += "<td>" + item.semesterName + "</td>";
    	rowHtml += "<td>" + item.projectName + "</td>";
    	rowHtml += "<td>" + item.studentSn + " " + item.studentName + "</td>";
    	rowHtml += "<td>" + item.gradeName + "</td>";
    	rowHtml += "<td>" + item.aidStatusName + "</td>";
    	rowHtml += "<td>" + item.aidAmount + "</td>";
    	rowHtml += "<td>" + item.pairStatusName + "</td>";
    	rowHtml += "<td>" + item.receiptFeedbackStatusName + "</td>";
    	rowHtml += "<td>" + item.summaryFeedbackStatusName + "</td>";
    	rowHtml += "<td>" + item.remark + "</td>";
    	rowHtml += "</tr>";
    	tableBody.append(rowHtml);
    });
}
